package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.dto.OrdersDto;
import com.itheima.entity.*;
import com.itheima.service.AddressBookService;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 订单信息分页查询
     * @param page
     * @param pageSize
     * @param beginTime
     * @param endTime
     * @return
     */
    //orders表少了个地址，只有地址ID，这时候需要参考菜品展示需要套餐分类
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize,String number,String beginTime,String endTime){
        //构造分页构造器
        Page<Orders> orderPage=new Page(page,pageSize);

        //要按顺序展示，故而需要进行条件查询
        LambdaQueryWrapper<Orders> lqw=new LambdaQueryWrapper<>();
        lqw.like(number!=null,Orders::getNumber,number);
        lqw.ge(beginTime!=null,Orders::getOrderTime,beginTime);
        lqw.le(endTime!=null,Orders::getOrderTime,endTime);
      /*  //添加排序条件，根据sort字段排序（注意是字段）
        lqw.orderByDesc(Dish::getUpdateTime);*/
        orderService.page(orderPage,lqw);

        //缺少用户名
        List<Orders> records = orderPage.getRecords();
        records = records.stream().map((item) -> {

            item.setUserName("用户" + item.getUserId());

            return item;
        }).collect(Collectors.toList());

        return R.success(orderPage);
/*
        //对象拷贝
        //提示：这里拷贝的是分页信息，并非实体类属性！
        //把菜品的分页信息（除了数据）复制给dto(因为dto要额外对数据处理)
        BeanUtils.copyProperties(orderPage,ordersDtoPage,"records");

        List<Orders> records=orderPage.getRecords();
        List<OrdersDto> list=records.stream().map((item)->{
            //创建dto对象，赋分类名值
            OrdersDto ordersDto = new OrdersDto();
            //由于创建的orders的属性为空，故而需要拷贝records子项目的数据
            BeanUtils.copyProperties(item,ordersDto);

            //获取订单的地址ID
            Long addressBookId = item.getAddressBookId();
            //获取地址
            AddressBook addressBook = addressBookService.getById(addressBookId);
            String detail = addressBook.getDetail();
            String cityName = addressBook.getCityName();
            String districtName = addressBook.getDistrictName();
            String provinceName = addressBook.getProvinceName();


            return dishDto;
        }).collect(Collectors.toList());
        //将处理后的数据传给页面，并传输修改后的页面信息给前端
        dtoPage.setRecords(list);*/
    }

    /**
     * 派送订单
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Orders orders){
        //TODO 构造条件构造器-修改构造器
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        //添加过滤条件
        updateWrapper.eq(Orders::getId, orders.getId());
        updateWrapper.set(Orders::getStatus,orders.getStatus());
        orderService.update(updateWrapper);
        return R.success("派送成功！");
    }

    /**
     * 移动端订单信息分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> orderPage(int page, int pageSize){
       //构造分页构造器
        Page<Orders> ordersPage=new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage=new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Orders> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, BaseContext.getCurrentId());
        //添加排序条件
        lqw.orderByDesc(Orders::getCheckoutTime);
        //执行查询
        orderService.page(ordersPage,lqw);

        //对象拷贝
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");

        List<Orders> orders=ordersPage.getRecords();
        List<OrdersDto> orderDtos=orders.stream().map((item)->{
            OrdersDto ordersDto = new OrdersDto();
            //先把dto继承的父类orders数据放进去
            BeanUtils.copyProperties(item,ordersDto);
            //再查询指定订单号下的订单细节和菜品件数
            Long id = item.getId();//getNumber也可以
            LambdaQueryWrapper<OrderDetail> lqw2=new LambdaQueryWrapper<>();
            lqw2.eq(OrderDetail::getOrderId,id);

            //查询出订单号下的订单细节数据
            List<OrderDetail> orderDetails = orderDetailService.list(lqw2);
            //设置dto的订单细节数据
            ordersDto.setOrderDetails(orderDetails);
            //设置商品件数
            ordersDto.setSumNum(orderDetails.size());

            return ordersDto;
        }).collect(Collectors.toList());
        //把修改后的记录放进去
        ordersDtoPage.setRecords(orderDtos);

        return R.success(ordersDtoPage);
    }
}